package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.dubbo.api.MovementsApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.dubbo.api.VideoApi;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongoDb.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Pan Rundong
 * @Date 2023-03-09 14:06
 * @Desc 后台管理Service
 */
@Service
public class ManageService {
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementsApi movementsApi;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户分页查找
     *
     * @param page
     * @param pagesize
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        // 1.调用api，查找对应用户信息
        IPage<UserInfo> pageInfo = userInfoApi.getPage(page, pagesize);
        // 2.返回PageResult
        return new PageResult(page, pagesize, (int) pageInfo.getTotal(), pageInfo.getRecords());
    }

    /**
     * 视频列表查询
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        // 调用api查询视频信息
        return videoApi.findVideosByPage(page, pagesize, uid);
    }

    /**
     * 根据用户Id查询用户信息
     *
     * @param userId
     * @return com.tanhua.model.domain.UserInfo
     * @Author Pan Rundong
     */
    public UserInfo findById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        if(redisTemplate.hasKey(Constants.FREEZE_USER+info.getId())) {
            info.setUserStatus("2");
        }
        return info;
    }

    /**
     * 查询动态
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        // 1.调用Api查询对应动态信息
        PageResult pageResult = movementsApi.findByState(page,pagesize,uid,state);

        // 2.获取动态对应userId
        List<Movement> movementsList = (List<Movement>) pageResult.getItems();
        List<Long> ids = CollUtil.getFieldValues(movementsList, "userId", Long.class);

        // 3.调用api查询userInfo信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(ids, null);

        // 4.封装Vo
        List<MovementsVo> voList = new ArrayList<>();
        for (Movement movement : movementsList) {
            UserInfo userInfo = userInfoMap.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);
        // 5.返回pageResult
        return pageResult;
    }

    /**
     * 用户冻结
     *
     * @param map
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Author Pan Rundong
     */
    public Map<String, String> freeze(Map map) {
        // 1.获得冻结时间以及用户Id
        Integer freezingTime = Integer.valueOf(map.get("freezingTime").toString());
        Long userId = AdminHolder.getUserId();

        // 2.判断冻结时间，设定冻结天数
        int day = 0;
        if (freezingTime == 1) {
            day = 3;
        } else if (freezingTime == 2){
            day = 7;
        } else if (freezingTime == 3) {
            day = -1;
        }

        // 3.转换map->JSON，存入Redis中，储存天数day
        String value = JSON.toJSONString(map);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER+userId,value,day, TimeUnit.MINUTES);

        // 4.返回冻结成功map
        Map mapFreeze = new HashMap();
        mapFreeze.put("message","冻结成功");
        return mapFreeze;
    }

    /**
     * 用户解冻
     *
     * @param map
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Author Pan Rundong
     */
    public Map<String, String> unFreeze(Map map) {
        // 1.获取用户id以及解冻原因
        String userId = map.get("userId").toString();
        // 2.删除Redis相关数据
        redisTemplate.delete(Constants.FREEZE_USER + userId);
        // 3.封装返回信心map
        Map<String, String> retMap = new HashMap<>();
        retMap.put("message", "解冻成功");
        // 4.返回
        return retMap;
    }
}
